from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models

def catesadd(request):
    if request.method=='GET':
        # cates = models.Cates.objects.all()
        cates = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')

        # 查询所有分类 分配数据
        return render(request,'myadmin/cates/add.html',{'info':cates})
    elif request.method=='POST':
        data = request.POST.dict()   # fname=0 name=手机  
        # 添加
        ob = models.Cates()
        ob.name=data['name']
        ob.pid=int(data['fname'])
        # 判断是否是顶级分类
        if ob.pid!=0:
            f=models.Cates.objects.get(id=data['fname'])  # id=0  [{object:objec}] <query:[{},{}]>
            ob.path=f.path+str(ob.pid)+','
        else:
            ob.path=data['fname']+','
           
        ob.save()
        return HttpResponse('ok')

def cateslist(request):
    # cates = models.Cates.objects.all()
    # 模型提供 extra
    ob = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    for x in ob:
        print(x.path.count(',')-1)
    #  顶级分类
        # 服装
        #     男装
        #         西装
        #     女装
        # 数码
        #     手机
    return render(request,'myadmin/cates/userlist.html',{'info':ob})
# 删除
def catesdel(request):
    # 获取要删除的分类的id
    cid = request.GET.get('id') 
    # 根据id去查询子分类
    ob = models.Cates.objects.filter(pid=cid)
    # 判断如果有子分类不删除
    if ob:
        return JsonResponse({'error':0,'msg':'有子分类不能删除'})
    else:
        z = models.Cates.objects.get(id=cid)
        z.delete()
        return JsonResponse({'error':1,'msg':'删除成功'})

def catesedit(request):
    # 接受数据
    data = request.GET.dict()
    try:
        # 更新数据
        ob = models.Cates.objects.get(id=data['id'])
        ob.name=data['name']
        ob.save()
        return JsonResponse({'error':1,'msg':'修改成功'})
    except:
        return JsonResponse({'error':0,'msg':'修改失败'})
   
